package com.zhouyiquan.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhouyiquan.common.utils.PageUtils;
import com.zhouyiquan.common.utils.Query;
import com.zhouyiquan.gulimall.product.dao.CategoryDao;
import com.zhouyiquan.gulimall.product.entity.CategoryEntity;
import com.zhouyiquan.gulimall.product.service.CategoryBrandRelationService;
import com.zhouyiquan.gulimall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(new Query<CategoryEntity>().getPage(params), new QueryWrapper<CategoryEntity>());

        return new PageUtils(page);
    }

    /**
     * 查询所有的分类、子分类、以树形结构显示出来
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {


        // 1、先获取所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 2、组装成父子结构
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            // 2.1、取出id为0的，就是一级分类
            return categoryEntity.getParentCid() == 0;

        }).map(menu -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());//取出所有的一级分类后，收集为List集合

        return level1Menus;

    }

    /**
     * 批量删除菜单分类
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否有被别处引用
        baseMapper.deleteBatchIds(asList);

    }


    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 及联更新
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }


    private List<Long> findParentPath(Long catelogId, List paths) {

        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);

        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }

        return paths;

    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root 当前的菜单
     * @param all  所有的菜单数据
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return root.getCatId() == categoryEntity.getParentCid();
        }).map(categoryEntity -> {
            // 找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            // 菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());

        }).collect(Collectors.toList());


        return children;
    }

}